package com.zhiche.lisa.core.utils;

import com.google.common.collect.Lists;
import com.zhiche.lisa.core.supports.BaseException;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.Arrays;
import java.util.List;



public class XmlUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(XmlUtil.class);


    /**
     * 将文件转换为xml文档
     * @param file
     * @return
     * @throws Exception
     */
    public static Document parseByFile(File file) throws Exception{
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(file);
        } catch (Exception e) {
            throw e;
        }
        return document;
    }

    /**
     * 通过文件路径解析xml文件
     * @param path 文件路径
     */
    public static Document parseByFilePath(String path) {
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(path);
        } catch (DocumentException e) {
            throw new BaseException(e.getMessage());
        }
        return document;
    }

    /**
     * 通过字符串解析xml文件
     */
    public static Document parseByString(String xml) throws Exception{
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(new ByteArrayInputStream( xml.getBytes("utf-8")));
        } catch (Exception e) {
            throw e;
        }
        return document;
    }


    /**
     * 根据文件路径得到所有的xml属性
     * @param filepath
     * @param xpath
     * @return
     */
    public static List<Attribute> getAttrListsByFilePath(String filepath, String xpath){
        List<Attribute> lists = Lists.newArrayList();
        File file = new File(filepath);
        if (file.isDirectory()) {
            List<String> filelist = Arrays.asList(file.list());
            filelist.forEach(filename -> {
                try {
                    Document document = XmlUtil.parseByFilePath(filepath + filename);
                    List<Node> list = document.selectNodes(xpath);
                    list.forEach(node -> {
                        if (node.getNodeType() == 1) {
                            Element element = (Element) node;
                            lists.addAll(element.attributes());
                        }
                    });
                } catch (Exception ex) {
                    LOGGER.error(ex.getMessage());
                }
            });
        }
        else{
            try {
                Document document = XmlUtil.parseByFilePath(filepath);
                List<Node> list = document.selectNodes(xpath);
                list.forEach(node -> {
                    if (node.getNodeType() == 1) {
                        Element element = (Element) node;
                        lists.addAll(element.attributes());
                    }
                });
            } catch (Exception ex) {
                LOGGER.error(ex.getMessage());
            }
        }
        return lists;
    }





    /**
     * 把文件转化为String
     * @param document
     * @return
     */
    public static String xmlToString(Document document) throws BaseException{
        String xmlString = "";
        try {
            xmlString=document.asXML();
        } catch (Exception e) {
            throw new BaseException(e.getMessage());

        }
        return xmlString;
    }

    /**
     * 文件转化为xml文档
     *
     * @param filePath
     * @return
     * @throws BaseException
     */
    public static Document getDocumentByFile(String filePath) throws BaseException {
        Document document = null;
        try {
            File file = ResourceUtils.getFile(filePath);
            if (file.exists()) {
                document = XmlUtil.parseByFile(file);
            }
        } catch (Exception ex) {
            throw new BaseException(ex.getMessage());
        }
        return document;
    }
}
